<?php
namespace App\Controllers\Admin;

use App\Controllers\Base;
class Users extends Base
{
    protected $db;
    function __construct(){
        $this->db = new \App\Models\Admin\Users();
    }

    // 数据
    public function data(){
        $this->actionAuth(true);
        $P = $this->U();
        $P['searchField'] = 'username,phone,email,nickname';
        $data = $this->db->asObject()->select('id,username,nickname,email,phone,avatarUrl,status,remark')
            ->search($P)->paginates($this->_page(),$this->_size());
        $db = new \App\Models\Admin\Roles();
        foreach ( $data['data'] as $item ) {
            $role_data = $db->where("id in ( select role_id from admin_users_role where user_id = {$item->id})")->findAll();
            $arr = [];
            foreach ( $role_data as $row ) $arr[] = $row['name'];
            $item->roles = join(',',$arr);
        }
        return $this->toJson($data);
    }

    // 编辑
    public function detail(){
        if ( $err = $this->actionAuth(true) )
            return $this->setError( $this->filed[$err] );
        $db = new \App\Models\Admin\UsersRoles();
        $Id = $this->U('id');
        if ( $Id && !$user_data = $this->db->select('id,username,nickname,phone,email,remark')->where('id',$Id )->first()) {
            return $this->setError('参数错误');
        }

        $data = [];
        if ( $Id ) {
            $ids = [];
            $ur_data = $db->select()->where('user_id', $Id)->findAll();
            foreach ($ur_data as $item) $ids[] = $item['role_id'];
            $user_data["roles"] = $ids;
        }
        $data['form_item'] = $this->_form($Id);
        $data['data'] = $user_data ?? [];
        return $this->toJson($data);
    }

    // 保存
    public function save(){
        if ( $err = $this->actionAuth(true) ) return $this->setError( $this->filed[$err] );
        $form = $this->U();
        if ( !$form['id'] && !$this->db->where('id',$form['id'])->first() ) $form['password'] = '888888';
        $this->db->setValidationMessages($this->db->validationMessages);
        if( $this->db->save($form) ) {
            $db = new \App\Models\Admin\UsersRoles();
            $form["id"] = $form["id"]?$form["id"]:$this->db->getInsertID();
            // 保存用户角色
            $db->batch_save($form["id"] , $form["roles"]);
            return $this->toJson('已保存');
        }
        return $this->setError($this->db->errors());
    }

    // 删除
    public function delete(){
        if ( $err = $this->actionAuth(true) ) return $this->setError( $this->filed[$err] );
        if( $this->db->delete($this->U('id')) )
            return $this->toJson('已删除');
        return $this->setError('删除失败');
    }

    // 密码重置
    public function spasswd(){
        $this->actionAuth(true);
        $v = $this->U('value');
        if ( $data = $this->db->where('id',$this->U('id'))->first()) {
            $data->password = $v;
            if($this->db->save($data))
                return $this->toJson('密码已重置为:'.$v);
        }
        return $this->setError('重置失败');
    }

    // 设置启用/禁用
    public function disenabled(){
        $this->actionAuth(true);
        if ( $data = $this->db->where('id',$this->U('id'))->first()) {
            if($this->db->where('id',$data['id'])->set('status',!$data['status'])->update())
                return $this->toJson("已成功设置");
        }
        return $this->setError("设置错误!");
    }

    // 重置密码
    public function setpasswd(){
        $this->actionAuth();
        $U = $this->U();
        if( session('id') == 0 ) return $this->setError('系统管理改不了密码');
        $model = $this->db->find(session('id'));
        if(md5($U['o'])  != $model->password)
            return $this->setError('原密码不正确');

        if($U['n'] != $U['r'])
            return $this->setError('原密码不正确');
        if( $this->db->save(['id'=>session('id'),'password'=>$U['n']]) ){
            return $this->toJson('密码已设置!');
        }
        return $this->setError('密码设置失败');
    }

    private function _form( $Id = 0, $roles = [] ){
        $power = new \App\Services\comm();
        $roles_data = $power->get_roles_data( $this->userId() );
        $form_item = [
            ["label"=> '登录帐户', 'field'=> 'username','placeholder'=>'请输入 登录帐户' ,'rules'=>[[ 'required'=> true, 'message'=> '请输入 登录帐户' ]]],
            [ 'label'=> '用户昵称', 'field'=> 'nickname','placeholder'=>'请输入 用户昵称' ,'rules'=>[[ 'required'=> true, 'message'=> '请输入 用户昵称' ]]],
            [ 'label'=> '手机号', 'field'=> 'phone','placeholder'=>'请输入 手机号' ,'rules'=>[[ 'required'=> true, 'message'=> '请输入 手机号' ]]],
            [ 'label'=> '邮箱', 'field'=> 'email','placeholder'=>'请输入 邮箱' ,'rules'=>[[ 'required'=> true, 'message'=> '请输入 邮箱' ]]],
            [ 'label'=> '角色','type'=>'checkbox', 'field'=> 'roles','placeholder'=>'请输选择 角色' ,'options' => ['data' => $roles_data],'rules'=>[[ 'required'=> true, 'message'=> '请选择 角色' ]]],
            [ 'label'=> '备注','type' => 'textarea', 'field'=> 'remark','placeholder'=>'请输入 备注' ]
        ];
        // if ( $Id ) unset($form_item[2]);
        //array_slice()
        return $form_item;
    }
}
